//
//  HomeFeaturedCell.m
//  SleepingElf
//
//  Created by karong on 2023/10/10.
//

#import "HomeFeaturedCell.h"
#import "GRHorizontalFlowLayout.h"
#import "FeaturedItemCell.h"

@interface HomeFeaturedCell ()
@property (weak, nonatomic) IBOutlet UICollectionView *listView;
@property (strong, nonatomic) NSArray *dataArray;
@property (strong, nonatomic) GRHorizontalFlowLayout *flowLayout;
@property (nonatomic, assign) CGSize itemSize;
@end

@implementation HomeFeaturedCell

- (GRHorizontalFlowLayout *)flowLayout {
    if (!_flowLayout) {
        _flowLayout = [[GRHorizontalFlowLayout alloc] initWithSectionInset:UIEdgeInsetsMake(0, 13, 0, 13) miniLineSapce:20 miniInterItemSpace:20 itemSize:self.itemSize];
    }
    return _flowLayout;
}

- (void)setDataWithObject:(NSArray *)object {
    self.dataArray = object;
    self.listView.width = self.bounds.size.width;
    self.listView.height = self.bounds.size.height;
    CGFloat width = floor((SEScreenWidth - 13 - 20 - 20) / 2.7);
    CGFloat height = width + 29;
    self.itemSize = CGSizeMake(width, height);
    self.flowLayout.itemSize = self.itemSize;
    self.flowLayout.sectionInset = UIEdgeInsetsZero;
    self.listView.collectionViewLayout = self.flowLayout;
    self.flowLayout.contentSize = CGSizeMake(object.count * (width + 20) + 13 + 13 - 20, height);
    [self.listView reloadData];
}


#pragma mark - UICollectionViewDelete

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    FeaturedItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"FeaturedItemCell" forIndexPath:indexPath];
    [cell setDataWithObject:self.dataArray[indexPath.row]];
    return cell;
}


#pragma mark - UICollectionViewDelegateFlowLayout

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 13, 0, 13);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 20;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return self.itemSize;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.delegate respondsToSelector:@selector(homeFeaturedCellDidSelectWithObject:)]) {
        [self.delegate homeFeaturedCellDidSelectWithObject:self.dataArray[indexPath.row]];
    }
    [self.listView reloadData];
}

@end
